package com.llap.exp190929.service;

import com.llap.exp190929.entity.Aqi;
import com.llap.exp190929.entity.District;
import com.llap.exp190929.repository.AqiRepository;
import com.llap.exp190929.repository.DistrictRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class AqiService {
    private AqiRepository aqiRepository;

    public Aqi findAQI(int id) {
        return aqiRepository.findById(id).orElse(null);
    }

    public Page<Aqi> findAQIs(int page, int pageSize, int districtId) {
        Pageable paginator = PageRequest.of(page - 1, pageSize);
        if (districtId > -1) {
            District district = new District();
            district.setId(districtId);
            return aqiRepository.findAllByDistrict(district, paginator);
        }
        return aqiRepository.findAll(paginator);
    }

    @Transactional
    public Aqi addAQI(Aqi aqi) {
        if (aqi.getId() != null) return null;
        return aqiRepository.save(aqi);
    }

    @Transactional
    public Aqi updateAQI(Aqi aqi) {
        if (aqi.getId() == null) return null;
        return aqiRepository.save(aqi);
    }

    @Transactional
    public void deleteAQI(int id) {
        aqiRepository.deleteById(id);
    }
}
